mod error;
mod header;
use header::TransferStatus;
use std::{
    env,
    io::{Read, Result, Write},
    net::{TcpListener, TcpStream},
};

fn main() -> Result<()> {
    env::set_var("RUST_LOG", "debug");
    env_logger::init();
    println!("程序开始运行");
    let listener = TcpListener::bind("127.0.0.1:7878")?;
    for stream in listener.incoming() {
        handle_client(stream?)?;
    }
    println!("停止运行");
    Ok(())
}

fn handle_client(mut stream: TcpStream) -> Result<()> {
    println!("addr: {}", stream.peer_addr().unwrap());
    let mut buf = [0; 1024];
    let length: i32 = 0;
    let mut status = TransferStatus::default();
    let mut pack_end: bool = false;
    loop {
        let mut number_bytes = [0u8; 2];
        match status {
            // 接受长度
            TransferStatus::Header => {
                status = TransferStatus::Body;
            }
            // 接受指定的长度
            TransferStatus::Body => {
                // 这儿需要判断是否接受完毕
                if pack_end {
                    status = TransferStatus::End;
                    continue;
                }
                status = TransferStatus::Ok;
            }
            TransferStatus::Ok => {
                status = TransferStatus::Header;
            }
            // 向客户端发送回执
            TransferStatus::End => {
                break;
            }
        };
        stream.read_exact(&mut number_bytes)?;
    }
    Ok(())
}
